package com.huitongmaoyi.ai.service;

import com.huitongmaoyi.ai.UserSessionHandler;
import com.huitongmaoyi.ai.dao.UserDAO;

import java.sql.SQLException;
import java.util.Scanner;
import java.io.PrintWriter;

public class ChatService {
    private final Scanner scanner;
    private final String currentUsername;
    private final UserDAO userDAO = new UserDAO();
    private final PrintWriter out;
    private final UserSessionHandler currentSession;

    // 保留控制台模式的兼容构造函数
    public ChatService(Scanner scanner, String currentUsername, PrintWriter out) {
        this.scanner = scanner;
        this.currentUsername = currentUsername;
        this.out = out;
        this.currentSession = null; // 控制台模式下为null
    }

    // 网络会话模式的构造函数
    public ChatService(Scanner scanner, String currentUsername, UserSessionHandler currentSession) {
        this.scanner = scanner;
        this.currentUsername = currentUsername;
        this.out = currentSession.getOut();
        this.currentSession = currentSession;
    }

    public void startChat() {
        try {
            out.println("\n=== 聊天系统 ===");
            out.println("1. 与客户聊天（功能待实现）");
            out.println("2. 与系统用户聊天（在线：" + UserSessionHandler.onlineUsers.keySet() + "）");
            out.println("3. 聊天室功能");
            out.println("4. 返回主菜单");
            out.println("请选择：");
            String choice = scanner.nextLine().trim();

            switch (choice) {
                case "1":
                    chatWithCustomer();
                    break;
                case "2":
                    chatWithUser();
                    break;
                case "3":
                    // 进入聊天室功能
                    new ChatRoomService(scanner, currentUsername, currentSession.getOut()).enterChatRoomMenu();
                    startChat(); // 返回聊天室菜单后显示聊天系统主菜单
                    break;
                case "4":
                    return;
                default:
                    out.println("无效选项");
                    startChat();
            }
        } catch (SQLException e) {
            out.println("聊天初始化失败：" + e.getMessage());
        }
    }

    private void chatWithCustomer() throws SQLException {
        out.println("进入客户聊天模式（功能待实现）");
        startChat();
    }

    private void chatWithUser() throws SQLException {
        out.println("当前在线用户：" + UserSessionHandler.onlineUsers.keySet());
        out.println("请输入私聊指令（格式：@用户名 消息内容，输入「返回」退出）：");

        while (true) {
            String input = scanner.nextLine().trim();
            if ("返回".equals(input)) {
                startChat();
                return;
            } else if (input.startsWith("@")) {
                handlePrivateChat(input);
            } else {
                out.println("格式错误！正确格式：@用户名 消息内容（例：@admin 你好），输入「返回」退出");
            }
        }
    }

    private void handlePrivateChat(String input) {
        try {
            int spaceIndex = input.indexOf(' ');
            if (spaceIndex == -1 || spaceIndex == input.length() - 1) {
                out.println("❌ 格式错误！正确格式：@用户名 消息内容（例：@admin 你好）");
                return;
            }

            String targetUsername = input.substring(1, spaceIndex).trim();
            String message = input.substring(spaceIndex + 1).trim();

            if (targetUsername.equals(currentUsername)) {
                out.println("❌ 不能给自己发送私聊消息！");
                return;
            }

            UserSessionHandler targetSession = UserSessionHandler.onlineUsers.get(targetUsername);
            if (targetSession == null) {
                out.println("❌ 用户「" + targetUsername + "」不在线或不存在！");
                return;
            }

            if (userDAO.getUserIdByUsername(targetUsername) == null) {
                out.println("❌ 用户「" + targetUsername + "」不存在！");
                return;
            }

            targetSession.getOut().println("\n📩 来自「" + currentUsername + "」的私聊：" + message);
            out.println("✅ 已发送私聊给「" + targetUsername + "」：" + message);

        } catch (Exception e) {
            out.println("❌ 私聊发送失败：" + e.getMessage());
        }
    }
}